package es.mgil.whoWantsToBeAMillonaire.activities;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import es.mgil.whoWantsToBeAMillonaire.R;
import es.mgil.whoWantsToBeAMillonaire.runnables.AddFriendRunnable;
import es.mgil.whoWantsToBeAMillonaire.runnables.GetAddressRunnable;
import es.mgil.whoWantsToBeAMillonaire.util.PreferencesKeys;

public class Settings extends Activity implements LocationListener {
	private EditText name;
	private EditText longitude;
	private EditText latitude;
	private EditText friend;
	private EditText seconds;
	public TextView addressTextView;
	public Button locateButton;
	public Button addressButton;
	private Button addFriendButton;

	private SharedPreferences preferences;
	private Editor editor;

	private boolean locationReceived = false;

	private GetAddressRunnable runnable;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_settings);

		// store the preferences
		preferences = getSharedPreferences(PreferencesKeys.SHARED_PREFERENCES,
				MODE_PRIVATE);
		editor = preferences.edit();

		// initialize some useful objects from interface
		name = (EditText) findViewById(R.id.settings_name);
		longitude = (EditText) findViewById(R.id.settings_longitude);
		latitude = (EditText) findViewById(R.id.settings_latitude);
		addressTextView = (TextView) findViewById(R.id.settings_textView_location);
		friend = (EditText) findViewById(R.id.settings_friend);
		locateButton = (Button) findViewById(R.id.settings_button_locate);
		addressButton = (Button) findViewById(R.id.settings_button_myAddress);
		addFriendButton = (Button) findViewById(R.id.settings_button_add_friend);
		seconds = (EditText) findViewById(R.id.settings_seconds);

		// load the settings values from the preferences
		loadSettings();

		// hide the software keyboard by default
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		runnable = new GetAddressRunnable(this);
	}

	@Override
	protected void onPause() {
		// save the settings
		saveSettings();

		// remove this listener from location services
		((LocationManager) getSystemService(LOCATION_SERVICE))
				.removeUpdates(this);

		super.onPause();
	}

	@Override
	public void onLocationChanged(Location location) {
		if (!locationReceived) {
			locationReceived = true;
			// when the location is changed when the listener is activated,
			// change
			// the values of the widgets
			if (location != null) {
				longitude.setText(String.valueOf(location.getLongitude()));
				latitude.setText(String.valueOf(location.getLatitude()));
				getAddress(location.getLongitude(), location.getLatitude());
			}

			// then, remove the listener
			((LocationManager) getSystemService(LOCATION_SERVICE))
					.removeUpdates(this);

			// and enable the location buttons again
			locationReceived = false;
		}
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	@Override
	public void onProviderEnabled(String provider) {
		// when a provider is enabled again, inform the user
		if (provider.equals(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, R.string.settings_gps_enabled,
					Toast.LENGTH_LONG).show();
		} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
			Toast.makeText(this, R.string.settings_wifi_enabled,
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		// when a provider is disabled, inform the user
		if (provider.equals(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, R.string.settings_gps_disabled,
					Toast.LENGTH_LONG).show();
		} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
			Toast.makeText(this, R.string.settings_wifi_disabled,
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Function to locate my position using GPS or WIFI/3G providers. If any
	 * error occurs while using any provider, remove the listener from location
	 * service
	 */
	public void locate(View view) {
		locateButton.setEnabled(false);
		addressButton.setEnabled(false);
		boolean error = false;
		try {
			((LocationManager) getSystemService(LOCATION_SERVICE))
					.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
							this);
		} catch (Exception e) {
			error = true;
			((LocationManager) getSystemService(LOCATION_SERVICE))
					.removeUpdates(this);
			locateButton.setEnabled(true);
			addressButton.setEnabled(true);
		}
		try {
			((LocationManager) getSystemService(LOCATION_SERVICE))
					.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
							0, 0, this);
		} catch (Exception e) {
			if (error) {
				((LocationManager) getSystemService(LOCATION_SERVICE))
						.removeUpdates(this);
				locateButton.setEnabled(true);
				addressButton.setEnabled(true);
			}
		}
	}

	/**
	 * Function that retrieves the address from a coordinates
	 */
	public void myAddress(View view) {
		try {
			locateButton.setEnabled(false);
			addressButton.setEnabled(false);
			double longitude = Double.valueOf(this.longitude.getText()
					.toString());
			double latitude = Double
					.valueOf(this.latitude.getText().toString());
			getAddress(longitude, latitude);
		} finally {
		}
	}

	/**
	 * Function to add a friend. Uses a runnable to do it
	 */
	public void addFriend(View view) {
		addFriendButton.setEnabled(false);
		String myName = name.getText().toString();
		String friendName = friend.getText().toString();
		new AddFriendRunnable(this, myName, friendName).addFriend();
	}

	/**
	 * Load Settings values from preferences
	 */
	private void loadSettings() {
		name.setText(preferences
				.getString(PreferencesKeys.PREFERENCES_NAME, ""));
		longitude.setText(String.valueOf(preferences.getFloat(
				PreferencesKeys.PREFERENCES_LONGITUDE, 0)));
		latitude.setText(String.valueOf(preferences.getFloat(
				PreferencesKeys.PREFERENCES_LATITUDE, 0)));
		addressTextView.setText(String.valueOf(preferences.getString(
				PreferencesKeys.PREFERENCES_ADDRESS, "")));
		seconds.setText(String.valueOf(preferences.getInt(
				PreferencesKeys.PREFERENCES_SECONDS, 30)));
	}

	/**
	 * Store Settings values to preferences
	 */
	private void saveSettings() {
		try {
			editor.putString(PreferencesKeys.PREFERENCES_NAME, name.getText()
					.toString());
			editor.putFloat(PreferencesKeys.PREFERENCES_LONGITUDE,
					Float.valueOf(longitude.getText().toString()));
			editor.putFloat(PreferencesKeys.PREFERENCES_LATITUDE,
					Float.valueOf(latitude.getText().toString()));
			editor.putString(PreferencesKeys.PREFERENCES_ADDRESS,
					addressTextView.getText().toString());
			editor.putInt(PreferencesKeys.PREFERENCES_SECONDS,
					Integer.parseInt(seconds.getText().toString()));
		} finally {
			editor.commit();
		}
	}

	/**
	 * Retrieve the Address from the given coordinates. Do it within a separated
	 * thread
	 */
	private void getAddress(double longitude, double latitude) {
		// start getting the address using a thread
		runnable.getAddress(longitude, latitude);
	}

}
